package com.xja.service.impl;


import com.xja.mapper.RoleMapper;
import com.xja.pojo.Role;
import com.xja.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<Role> findList() {
        return this.roleMapper.selectByExample(null);
    }

    @Override
    public Role findRoleById(Integer id) {
        return this.roleMapper.selectByPrimaryKey(id);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void addRole(Role role, Integer[] ps) {
        roleMapper.insert(role);
        int roleId = role.getId();
        //System.out.println(roleId);
        roleMapper.addRolePermission(roleId,9);
        if(ps!=null)
            for(Integer s:ps)
                roleMapper.addRolePermission(roleId,s);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void updateRole(Role role, Integer[] ps) {
        roleMapper.updateByPrimaryKey(role);
        if(ps==null){
            roleMapper.delAllRolePermission(role.getId());
        }else {
            for(Integer i:ps){
                int flag = roleMapper.findFlagByRidPid(role.getId(), i);
                if(flag == 0) {
                    roleMapper.addRolePermission(role.getId(), i);
                }
                else{
                    roleMapper.updateRolePermission(role.getId(), i);
                }
            }
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void deleteRole(Integer roleId) {
        roleMapper.deleteByPrimaryKey(roleId);
        roleMapper.deleteRolePermissionByRoleId(roleId);
    }


}
